package com.powernode.service.impl;

import com.powernode.dto.AppUserDto;
import com.powernode.dto.Result;
import com.powernode.feign.FeignUmsService;
import com.powernode.model.User;
import com.powernode.service.UserService;
import com.powernode.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private FeignUmsService feignUmsService;

    @Override
    public UserDetails loadUserByMobileAndCode(String mobile, String code) {
        // 调用远程接口获取用户对象
        Result<AppUserDto> result = feignUmsService.getAppUserByMobileAndCode(mobile, code);
        // 如果状态码不等于200，抛出异常
        if (result.getCode() != HttpStatus.OK.value()) {
            throw new OAuth2AuthenticationException(new OAuth2Error(String.valueOf(result.getCode())),result.getMessage());
        }
        // 获取用户对象
        AppUserDto appUserDto = result.getData();
        // 设置初始密码为 111111
        User user = new User(
                appUserDto.getId(),
                appUserDto.getUsername(),
                appUserDto.getMobile(),
                new BCryptPasswordEncoder().encode("111111"),
                AuthorityUtils.commaSeparatedStringToAuthorityList(appUserDto.getGroupName()));
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 远端调用接口获取用户对象
        Result<AppUserDto> result = feignUmsService.getAppUserByUsername(username);
        AppUserDto appUserDto = result.getData();
        // 如果用户不存在抛出异常
        if (appUserDto == null) {
            // String.valueOf 和 toString 区别，String.valueOf有判空功能，toString没有
            throw new OAuth2AuthenticationException(new OAuth2Error(String.valueOf(result.getCode())), result.getMessage());
        }
        // 设置初始密码为 111111
        return new User(
                appUserDto.getId(),
                appUserDto.getUsername(),
                appUserDto.getMobile(),
                new BCryptPasswordEncoder().encode("111111"),
                AuthorityUtils.commaSeparatedStringToAuthorityList(appUserDto.getGroupName())
        );
    }
}
